#    Supsta
#    Copyright (c) 2014 Sebastian Dufner
#
#    This file is part of Supsta.
#
#    Supsta is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    Supsta is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

require 'tempfile'

require 'supsta/gimp/image'

module Supsta

  ##
  # Module providing functionality to create GIMP Script-fu scripts.

  module Gimp

    ##
    # The GIMP application.

    class Application
      include Scope

      def initialize
        @nvars = 0
        @script = ''
      end
      attr_reader :script, :name, :scope

      ##
      # Runs the current program.
      # Variables and the program are reset after execution.
      #
      # *Note:* Apart from GIMP's messages to STDERR this doesn't provide
      # feedback on execution errors.

      def run
        tmp = Tempfile.new('supsta.scm')
        tmp.write script
        tmp.close

        fail 'Command exeuction failed. Do you have the GIMP installed?' unless
          system("gimp-console -nb \"(load \\\"#{tmp.path}\\\")\" -b \"(gimp-quit 1)\"")

        tmp.unlink

        @nvars = 0
        @script = ''

        nil
      end
      alias_method :execute, :run

      ##
      # Assign +value+ to variable +name+ in the current scope.

      def def(name, value)
        @script.concat "(define #{name} #{value})\n"

        nil
      end

    private

      attr_accessor :nvars

    end
  end
end
